﻿using iService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using Microsoft.VisualBasic;
using Service;
using swiftCode.Bbs.Model;
using swiftCode.Bbs.Model.Model;
using System.Linq.Expressions;
using static Microsoft.Extensions.Logging.EventSource.LoggingEventSource;

namespace swiftCode.Bbs.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class PostController : ControllerBase
    {
        private readonly IPostService _postService;
        private readonly IBanRecordService _banRecordService;
        private readonly IUserService _userService;
        private readonly IModuleService _moduleService;
        public PostController(IPostService postService, IBanRecordService banRecordService, IUserService userService, IModuleService moduleService)
        {
            _postService = postService;
            _banRecordService = banRecordService;
            _userService = userService;
            _moduleService = moduleService;
        }

        //private readonly IPostService _postService = new PostService();
        //private readonly IBanRecordService _banRecordService = new BanRecordService();
        //private readonly IUserService _userService = new UserService();


        /// <summary>
        /// 获取所有文章
        /// </summary>
        /// <returns></returns>
        [HttpGet(Name ="getAll")]
        public async Task<MessageModel<List<Post>>> getAll()
        {
            var post = await _postService.GetAllArticles();
            return new MessageModel<List<Post>>()
            {
                success = post.Count == 0 ? false : true,
                msg = post.Count == 0 ? "未找到符合条件的内容" : "搜索成功",
                response = post.Count == 0 ? null : post
            };
        }

        /// <summary>
        /// 关键字查询
        /// </summary>
        /// <param name="keyWord"></param>
        /// <returns></returns>
        [HttpGet(Name = "KeyWordSelect")]
        public async Task<MessageModel<List<Post>>> keyWordSelect(string keyWord)
        {
            var post = await _postService.SelectArticle(d => d.content.Contains(keyWord));
            return new MessageModel<List<Post>>()
            {
                success = post.Count == 0 ? false : true,
                msg = post.Count == 0 ? "未找到符合条件的内容" : "搜索成功",
                response = post.Count == 0 ? null : post,
            };
        }

        /// <summary>
        /// 标题查询
        /// </summary>
        /// <param name="keyWord"></param>
        /// <returns></returns>
        [HttpGet(Name = "TitleSelect")]
        public async Task<MessageModel<List<Post>>> TitleSelect(string keyWord)
        {
            var post = await _postService.SelectArticle(d => d.Title.Contains(keyWord));
            return new MessageModel<List<Post>>()
            {
                success = post.Count == 0 ? false : true,
                msg = post.Count == 0 ? "未找到符合条件的内容" : "搜索成功",
                response = post.Count == 0 ? null : post
            };
        }


        /// <summary>
        /// 文章编号查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet(Name = "IdSelect")]
        public async Task<MessageModel<List<Post>>> IDSelect(int id)
        {
            var post = await _postService.SelectArticle(d => d.PostId == id);
            return new MessageModel<List<Post>>()
            {
                success = post.Count == 0 ? false : true,
                msg = post.Count == 0 ? "未找到符合条件的内容" : "搜索成功",
                response = post.Count == 0 ? null : post
            };
        }

        /// <summary>
        /// 模块搜索 
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        [HttpGet(Name = "ModuleSelect")]
        public async Task<MessageModel<List<Post>>> ModuleSelect(string moduleName)
        {
            var module = await _moduleService.GetModule(d => d.ModuleName == moduleName);
            var post = await _postService.SelectArticle(d => d.Module == module.ModuleId);
            return new MessageModel<List<Post>>()
            {
                success = post.Count == 0 ? false : true,
                msg = post.Count == 0 ? "未找到符合条件的内容" : "搜索成功",
                response = post.Count == 0 ? null : post
            };
        }

        /// <summary>
        /// 作者搜索
        /// </summary>
        /// <param name="poster"></param>
        /// <returns></returns>
        [HttpGet(Name = "PosterSelect")]
        public async Task<MessageModel<List<Post>>> PosterSelect(string poster)
        {
            User user = await _userService.selectUser(d => d.UserName == poster);
            if(user == null)
            {
                return new MessageModel<List<Post>>()
                {
                    success = false,
                    msg = "未找到该作者",
                    response = null
                };
            }
            else
            {
                var post = await _postService.SelectArticle(d => d.Poster == user.UserId);
                return new MessageModel<List<Post>>()
                {
                    success = post.Count == 0 ? false : true,
                    msg = post.Count == 0 ? "该作者未发布过文章" : "搜索成功",
                    response = post.Count == 0 ? null : post,
                };
            }   
        }

        /// <summary>
        /// 发布新文章
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        [HttpGet(Name = "insert")]
        public async Task<MessageModel<String>> InsertArticle(int userId, string title, string module, string content)
        {
            BanRecord banUser = await _banRecordService.selectBanUser(d => d.UserId == userId);
            User user = await _userService.selectUser(d => d.UserId == userId);
            if(banUser != null) 
            {
                return new MessageModel<String>()
                {
                    success = false,
                    msg = "封禁中无法发布文章"
                };
            }
            else if(user == null)
            {
                return new MessageModel<String>()
                {
                    success = false,
                    msg = "账户已经注销"
                };
            }
            else
            {
                Post post = new Post();
                var Module = await _moduleService.GetModule(d => d.ModuleName == module);
                post.Title = title;
                post.Module = Module.ModuleId;
                post.Poster = userId;
                post.postTime = DateTime.Now;
                post.content = content;
                post.CountOfLikes = 0;
                post.picture = null;
                await _postService.PostArticle(post, true);
                return new MessageModel<String>()
                {
                    success = true,
                    msg = "发布成功"
                };
            }
        }

        /// <summary>
        /// 删除文章
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet(Name = "delete")]
        public async Task<MessageModel<String>> DeleteArticle(int id)
        {
            var entity = await _postService.GetAsync(d => d.PostId == id);
            if (entity != null)
            {
                await _postService.DeleteArticleById(d => d.PostId == id, true);
                return new MessageModel<String>()
                {
                    success = true,
                    msg = "删除成功"
                };
                
            }
            else
            {
                return new MessageModel<String>()
                {
                    success = false,
                    msg = "删除失败"
                };
            }
        }

        /// <summary>
        /// 更新文章
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet(Name = "update")]
        public async Task<MessageModel<String>> UpdateArticle(int postId, string title, string content)
        {
            var post = await _postService.FindAsyncNoTrack(d => d.PostId == postId);
            if (post != null)
            {
                post.Title = title;
                post.content = content;
                await _postService.UpdateArticle(post, true);
                return new MessageModel<String>()
                {
                    success = true,
                    msg = "修改成功"
                };
            }
            else
            {
                return new MessageModel<String>()
                {
                    success = false,
                    msg = "修改失败"
                };
            }
        }

        /// <summary>
        /// 点赞
        /// </summary>
        /// <param name="postId"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpGet(Name = "like")]
        public async Task<MessageModel<Post>> like(bool liked, int postId)
        {
            var post = await _postService.FindAsyncNoTrack(d => d.PostId == postId);
            if (post != null)
            {
                if (liked)
                {
                    post.CountOfLikes++;
                }
                else
                {
                    post.CountOfLikes--;
                }           
                await _postService.UpdateArticle(post, true);
                return new MessageModel<Post>()
                {
                    success = true,
                    msg = "点赞成功",
                    response = post
                };
            }
            else
            {
                return new MessageModel<Post>()
                {
                    success = false,
                    msg = "点赞失败",
                };
            }
        }
    }
}
